package com.yupi.yuoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.model.dto.content.ContentQueryRequest;
import com.yupi.yuoj.model.entity.Content;
import com.yupi.yuoj.model.entity.ContentCollection;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.vo.ContentVO;
import com.yupi.yuoj.service.ContentCollectionService;
import com.yupi.yuoj.service.ContentService;
import com.yupi.yuoj.mapper.ContentCollectionMapper;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author admin
* @description 针对表【content_collection(内容收藏表)】的数据库操作Service实现
* @createDate 2025-11-01 21:28:54
*/
@Service
public class ContentCollectionServiceImpl extends ServiceImpl<ContentCollectionMapper, ContentCollection>
    implements ContentCollectionService{

    @Resource
    private ContentService contentService;

    @Override
    public int doContentCollection(long contentId, User loginUser) {
        // 判断实体是否存在，根据类别获取实体
        Content content = contentService.getById(contentId);
        if (content == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已收藏
        long userId = loginUser.getId();
        // 每个用户串行收藏
        // 锁必须要包裹住事务方法
        ContentCollectionService contentCollectionService = (ContentCollectionService) AopContext.currentProxy();
        synchronized (String.valueOf(userId).intern()) {
            return contentCollectionService.doContentCollectionInner(userId, contentId);
        }
    }

    /**
     * 封装了事务的方法
     *
     * @param userId
     * @param contentId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int doContentCollectionInner(long userId, long contentId) {
        ContentCollection contentCollection = new ContentCollection();
        contentCollection.setUser_id(userId);
        contentCollection.setContent_id(contentId);
        QueryWrapper<ContentCollection> contentCollectionQueryWrapper = new QueryWrapper<>(contentCollection);
        ContentCollection oldContentCollection = this.getOne(contentCollectionQueryWrapper);
        boolean result;
        // 已收藏
        if (oldContentCollection != null) {
            result = this.remove(contentCollectionQueryWrapper);
            if (result) {
                // 收藏数 - 1
                result = contentService.update()
                        .eq("id", contentId)
                        .gt("favour_num", 0)
                        .setSql("favour_num = favour_num - 1")
                        .update();
                return result ? -1 : 0;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        } else {
            // 未收藏
            result = this.save(contentCollection);
            if (result) {
                // 收藏数 + 1
                result = contentService.update()
                        .eq("id", contentId)
                        .setSql("favour_num = favour_num + 1")
                        .update();
                return result ? 1 : 0;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
    }

    @Override
    public Page<ContentVO> listContentCollectionByPage(Page<Object> page, ContentQueryRequest contentQueryRequest, Long userId) {
        if (userId == null) {
            return new Page<>();
        }
        // 查询收藏的内容id
        QueryWrapper<ContentCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.select("content_id");
        List<ContentCollection> contentCollectionList = this.list(queryWrapper);
        
        // 获取内容id列表
        Set<Long> contentIdSet = contentCollectionList.stream()
                .map(ContentCollection::getContent_id)
                .collect(Collectors.toSet());
        
        if (contentIdSet.isEmpty()) {
            return new Page<>();
        }
        
        // 查询内容信息
        QueryWrapper<Content> contentQueryWrapper = new QueryWrapper<>();
        contentQueryWrapper.in("id", contentIdSet);
        
        // 根据收藏时间倒序
        contentQueryWrapper.orderByDesc("create_time");
        
        Page<Content> contentPage = contentService.page(new Page<>(page.getCurrent(), page.getSize()), contentQueryWrapper);
        
        // 转换为ContentVO
        List<ContentVO> contentVOList = contentPage.getRecords().stream()
                .map(content -> contentService.getContentVO(content, null))
                .collect(Collectors.toList());
        
        Page<ContentVO> contentVOPage = new Page<>(page.getCurrent(), page.getSize(), contentPage.getTotal());
        contentVOPage.setRecords(contentVOList);
        
        return contentVOPage;
    }

}




